package com.wuzheng.wisgo.sanitation.cloud.service.transfer.impl;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.wuzheng.wisgo.sanitation.cloud.constant.ErrorConst;
import com.wuzheng.wisgo.sanitation.cloud.model.transfer.param.TransferRouteAddParam;
import com.wuzheng.wisgo.sanitation.cloud.model.transfer.param.TransferRouteListParam;
import com.wuzheng.wisgo.sanitation.cloud.model.transfer.pojo.TransferRouteDTO;
import com.wuzheng.wisgo.sanitation.cloud.paraandgetutil.Exceptions;
import com.wuzheng.wisgo.sanitation.cloud.paraandgetutil.VehicleException;
import com.wuzheng.wisgo.sanitation.cloud.repository.entity.transfer.TransferRoute;
import com.wuzheng.wisgo.sanitation.cloud.repository.entity.transfer.TransferRouteTrash;
import com.wuzheng.wisgo.sanitation.cloud.repository.mapper.transfer.TransferRouteMapper;
import com.wuzheng.wisgo.sanitation.cloud.repository.mapper.transfer.TransferRouteTrashMapper;
import com.wuzheng.wisgo.sanitation.cloud.service.transfer.TransferRouteService;
import com.wuzheng.wisgo.sanitation.cloud.service.transfer.TransferRouteTrashService;
import com.wuzheng.wisgo.sanitation.framework.base.service.impl.BaseServiceImpl;
import com.wuzheng.wisgo.sanitation.framework.core.constant.SysRespEnum;
import com.wuzheng.wisgo.sanitation.framework.core.util.ServiceAssert;
import com.wuzheng.wisgo.sanitation.framework.util.BeanUtils;
import com.wuzheng.wisgo.sanitation.framework.util.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author：hoipang
 * @date：Created in 2019-12-06
 * @description：转运路线服务实现类
 * @modified By：
 * @version: 1.0
 */
@Service
public class TransferRouteServiceImpl extends BaseServiceImpl<TransferRoute> implements TransferRouteService {

    @Autowired
    private TransferRouteService transferRouteService;

    @Autowired
    private TransferRouteTrashService transferRouteTrashService;

    @Autowired
    private TransferRouteTrashMapper transferRouteTrashMapper;

    @Override
    public List<TransferRouteDTO> pageTransferRouteDTOs(TransferRouteListParam transferRouteListParam) {
        Page<TransferRouteDTO> page = new Page<>(transferRouteListParam.getPageIndex(),
                transferRouteListParam.getPageSize());
        TransferRouteMapper transferRouteMapper = this.getMapper(TransferRouteMapper.class);
        return transferRouteMapper.pageTransferRouteDTOs(page, transferRouteListParam.getRouteName());
    }

    @Override
    public void removeTransferRoutes(List<String> list) {
        ServiceAssert.isTrue(list != null && !list.isEmpty(), SysRespEnum.ILLEGAL_ARGUMENT.getCode(),
                ErrorConst.Common.ARGUMENT_NOT_NULL);
        List<TransferRoute> routeList = new ArrayList<>();
        list.stream().forEach(id -> {
            TransferRoute transferRoute = new TransferRoute();
            transferRoute.setId(id);
            transferRoute.setDeFlag(true);
            routeList.add(transferRoute);
        });
        this.updateBatchById(routeList, routeList.size());
        //关系表处理
        if(routeList.size()>0){
            for(TransferRoute transferRoute:routeList){
                List<TransferRouteTrash> transferRouteId = transferRouteTrashService.selectList("transfer_route_id", transferRoute.getId());
                if(transferRouteId.size()>0){
                    ArrayList<String> collect = transferRouteId.stream().map(TransferRouteTrash::getId).distinct().collect(Collectors.toCollection(ArrayList::new));
                    transferRouteTrashService.deleteBatchIds(collect);
                }
            }
        }
    }

    @Override
    public void addTransferRoutes(TransferRouteAddParam transferRouteAddParam) throws VehicleException {

        //先校验非空字段
        this.check(transferRouteAddParam);
        //插入主表数据
        TransferRoute transferRoute=new TransferRoute();
        transferRoute.setId(UUID.randomUUID().toString());
        transferRoute.setCustomerId(transferRouteAddParam.getCustomerId());
        transferRoute.setCustomerName(transferRouteAddParam.getCustomerName());
        transferRoute.setRemark(StringUtils.isEmpty(transferRouteAddParam.getRemark())?"":transferRouteAddParam.getRemark());
        transferRoute.setRouteName(transferRouteAddParam.getRouteName());
        transferRoute.setTrashNum(transferRouteAddParam.getTrashNum());
        transferRoute.setDeFlag(false);
        transferRoute.setCreator("local");
        transferRoute.setCreateTime(new Date());
        transferRoute.setModifier("local");
        transferRoute.setModifyTime(new Date());
        transferRoute.setIpAddress("120.0.0.1");
        transferRouteService.insert(transferRoute);
        //处理关系表
        if(!StringUtils.isEmpty(transferRouteAddParam.getTrashId())){
            logger.info("垃圾桶id:"+transferRouteAddParam.getTrashId());
            String[] trashIdArr = transferRouteAddParam.getTrashId().split(",");
            //处理ba_transfer_toute_trash
            this.insertTranferRouteTrash(transferRoute.getId(),trashIdArr,"add");
        }
    }

    @Override
    public TransferRouteAddParam selectTransferRouteById(String id) throws VehicleException {
        TransferRouteAddParam routeAddParam=new TransferRouteAddParam();
        if(StringUtils.isEmpty(id)){
            throw Exceptions.VehicleException("id不能为空！");
        }
        TransferRoute transferRoute = transferRouteService.selectById(id);
        if(transferRoute==null){
            throw Exceptions.VehicleException("查询转运路线失败！");
        }
        BeanUtils.copy(transferRoute,routeAddParam);
        if(StringUtils.isEmpty(transferRoute.getId())){
            throw Exceptions.VehicleException("数据异常，转运路线id为空！");
        }
        List<TransferRouteAddParam> transferRouteAddParams = transferRouteTrashMapper.selectTrasfNameByRouteId(transferRoute.getId());
        if(transferRouteAddParams.size()>0){
            String facilityNames = transferRouteAddParams.stream().map(TransferRouteAddParam::getFacilityName).collect(Collectors.toCollection(ArrayList::new)).toString();
            String faciName = facilityNames.substring(1, facilityNames.length() - 1);
            routeAddParam.setFacilityName(faciName);
        }
        return routeAddParam;
    }

    @Override
    public void updateTransferRoutes(TransferRouteAddParam transferRouteAddParam) throws VehicleException {
        this.check(transferRouteAddParam);
        TransferRoute transferRoute=new TransferRoute();
        BeanUtils.copy(transferRouteAddParam,transferRoute);
        if(StringUtils.isEmpty(transferRouteAddParam.getId())){
            throw Exceptions.VehicleException("数据修改失败：id不能为空！");
        }
        transferRouteService.updateById(transferRoute);
        List<TransferRouteTrash> transferRouteId = transferRouteTrashService.selectList("transfer_route_id", transferRouteAddParam.getId());
        if(transferRouteId.size()>0){
            for(TransferRouteTrash transferRouteTrash:transferRouteId){
                transferRouteTrash.setDeFlag(true);
                transferRouteTrashService.updateById(transferRouteTrash);
            }
        }
        String[] trashIdArr = transferRouteAddParam.getTrashId().split(",");
        //处理ba_transfer_toute_trash
        this.insertTranferRouteTrash(transferRoute.getId(),trashIdArr,"edit");
    }

    /*
     * @Description: 插入关系表数据
     * @Param: [tranferId, trashIdArr]
     * @Author: sunpeng
     * @Date: 2019/12/11
    **/
    public void insertTranferRouteTrash(String tranferId,String[] trashIdArr,String type) throws VehicleException {
        if(trashIdArr.length>0){
            for(int i=0;i<trashIdArr.length;i++){
                if(type.equals("add")){
                    EntityWrapper<TransferRouteTrash> wrapper=new EntityWrapper<>();
                    wrapper.eq("trash_id",trashIdArr[i]).eq("de_flag",false);
                    List<TransferRouteTrash> transferRouteTrashes = transferRouteTrashService.selectList(wrapper);
                    if(transferRouteTrashes.size()>0){
                      throw  Exceptions.VehicleException("当前垃圾桶已经绑定，不允许多次绑定，id："+trashIdArr[i]);
                    }
                }else if(type.equals("edit")){
                    EntityWrapper<TransferRouteTrash> wrapper=new EntityWrapper<>();
                    wrapper.eq("trash_id",trashIdArr[i]).eq("de_flag",true);;
                    List<TransferRouteTrash> transferRouteTrashes = transferRouteTrashService.selectList(wrapper);
                    if(transferRouteTrashes.size()>0){
                        throw  Exceptions.VehicleException("当前垃圾桶已经绑定，不允许多次绑定，id："+trashIdArr[i]);
                    }
                }
                TransferRouteTrash transferRouteTrash=new TransferRouteTrash();
                transferRouteTrash.setId(UUID.randomUUID().toString());
                transferRouteTrash.setTransferRouteId(tranferId);
                transferRouteTrash.setTrashId(trashIdArr[i]);
                transferRouteTrash.setDeFlag(false);
                transferRouteTrash.setCreator("local");
                transferRouteTrash.setCreateTime(new Date());
                transferRouteTrash.setModifier("local");
                transferRouteTrash.setModifyTime(new Date());
                transferRouteTrash.setIpAddress("120.0.0.1");
                transferRouteTrashService.insert(transferRouteTrash);
            }
        }
    }

    public void check(TransferRouteAddParam transferRouteAddParam) throws VehicleException {
        //字段校验
        if(transferRouteAddParam.getTrashNum()==null){
            throw Exceptions.VehicleException("垃圾桶数量不能为空！");
        }
        if(transferRouteAddParam.getTrashNum().compareTo(0)<=0){
            throw Exceptions.VehicleException("垃圾桶数量不能为0！");
        }
    }
}
